<template>
  <el-card class="w-full pt-[5px]">
    <CheckType v-model="searchForm.checkStatus" @typeChange="handleSearch" :countMap="countMap" />
    <el-form :model="searchForm" class="mt-[20px]" label-width="96px" ref="searchFormRef">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="合同编号" class="mb-[0px]" prop="code">
            <el-input v-model="searchForm.code" placeholder="合同编号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同名称" class="mb-[0px]" prop="name">
            <el-input v-model="searchForm.name" placeholder="合同名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同负责人" class="mb-[0px]" prop="chargerName">
            <el-input v-model="searchForm.chargerName" placeholder="合同负责人" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div class="flex justify-end">
            <el-button type="primary" @click="searchFormOpen = !searchFormOpen"
              >更多
              <el-icon color="#fff">
                <CaretTop v-show="searchFormOpen" />
                <CaretBottom v-show="!searchFormOpen" />
              </el-icon>
            </el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mt-[20px]" v-show="searchFormOpen">
        <el-col :span="6">
          <el-form-item label="" label-width="0">
            <el-input
              v-model="searchForm.feeAuthorizeMin"
              placeholder="最小合同金额"
              clearable
              style="width: calc(50% - 10px)"
              @input="fomateNumber(searchForm, 'feeAuthorizeMin', $event)"
            />
            <span style="width: 20px; text-align: center">至</span>
            <el-input
              v-model="searchForm.feeAuthorizeMax"
              placeholder="最大合同金额"
              clearable
              style="width: calc(50% - 10px)"
              @input="fomateNumber(searchForm, 'feeAuthorizeMax', $event)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属单位" prop="unitId">
            <CustomTreeSelect
              placeholder="所属单位"
              v-model="searchForm.unitId"
              valueKey="codeColumn"
              labelKey="valueColumn"
              :isFetch="false"
              :dataList="unitList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="原项目名称" prop="sourceProjectName">
            <el-input v-model="searchForm.sourceProjectName" placeholder="原项目名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="原项目分类" prop="sourceProjectType">
            <CustomTreeSelect
              paramsName="项目分类（所有-有级联）"
              placeholder="原项目分类"
              v-model="searchForm.sourceProjectType"
              valueKey="id"
              labelKey="label"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="原项目负责人" prop="sourceChargerName">
            <el-input v-model="searchForm.sourceChargerName" placeholder="原项目负责人" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="负责人电话" prop="chargerTel">
            <el-input v-model="searchForm.chargerTel" placeholder="负责人电话" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同状态" prop="projectStatusId">
            <CommonSelect
              paramsName="项目状态"
              placeholder="合同状态"
              v-model="searchForm.projectStatusId"
              valueKey="code"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供方单位" prop="yfUnitName">
            <el-input v-model="searchForm.yfUnitName" placeholder="供方单位" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="供方社会信用代码" label-width="140" prop="yfCode">
            <el-input v-model="searchForm.yfCode" placeholder="供方社会信用代码" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="供方联系人名称" label-width="140" prop="yfChargerName">
            <el-input v-model="searchForm.yfChargerName" placeholder="供方联系人名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供方电话" prop="yfTel">
            <el-input v-model="searchForm.yfTel" placeholder="供方电话" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="审核状态" prop="checkStatusArr">
            <CustomTreeSelect
              placeholder="审核状态"
              v-model="searchForm.checkStatusArr"
              valueKey="dictValue"
              labelKey="dictLabel"
              :isFetch="false"
              :dataList="checkStatusList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <CommonDateSelect
            placeholder="签订日期"
            v-model:startTime="searchForm.authorizeDateStart"
            v-model:endTime="searchForm.authorizeDateEnd"
          />
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card class="w-full pt-[5px] mt-[10px]">
    <div class="mb-[20px]">
      <el-button type="primary" @click="handleAdd" v-if="verifyRoleType.isKyryOrkycgly()">
        <el-icon class="mr-[5px]"><Plus /></el-icon>
        新增
      </el-button>
      <template v-if="verifyRoleType.isKymsOrkycgly()">
        <el-button @click="handleDelSelect">
          <el-icon class="mr-[5px]"><DeleteFilled /></el-icon>
          删除
        </el-button>
        <el-button @click="exportVisible = true">
          <svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出
        </el-button>
      </template>
    </div>
    <el-table
      :data="tableData"
      class="w-full"
      stripe
      row-key="id"
      v-loading="loading"
      ref="tableRef"
    >
      <el-table-column
        type="selection"
        width="40"
        :selectable="(row) => row.checkstatus != 1 && row.checkstatus != 2"
        v-if="!verifyRoleType.isKyry()"
      />
      <el-table-column prop="code" label="合同编号" width="115" />
      <el-table-column prop="name" label="合同名称">
        <template #default="{ row }">
          <el-link type="primary" @click="handleView(row.id)">{{ row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="chargerName" label="合同负责人" width="90">
        <template #default="{ row }">
          <el-link
            type="primary"
            @click="handleViewPerson(row.chargerCode)"
            v-if="row.chargerCode"
            >{{ row.chargerName }}</el-link
          >
          <span v-else>{{ row.chargerName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="authorizeDate" label="签订日期" width="100"/>
      <el-table-column prop="feeAuthorize" label="合同金额（万元）" width="95"/>
      <el-table-column prop="unit" label="所属单位" width="120">
        <template #default="{ row }">
          <CommonTreeLabel
            :dataList="unitList"
            valueKey="codeColumn"
            labelKey="valueColumn"
            :value="row.unitId"
          />
        </template>
      </el-table-column>
      <el-table-column prop="checkstatus" label="审核状态" width="100">
        <template #default="{ row }">
          <CommonLabel
            :dataList="checkStatusList"
            valueKey="dictValue"
            labelKey="dictLabel"
            :value="row.checkstatus"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200" align="center">
        <template #default="{ row }">
          <!-- -1:暂存 1:审批中 2:审核通过 3:审核不通过 -2:待完善 -->
          <!-- 科研人员 -->
          <template v-if="verifyRoleType.isKyry()">
            <template v-if="[-1, 3].includes(Number(row.checkstatus))">
              <el-button type="primary" size="small" plain @click="handleEdit(row.id)">
                编辑
              </el-button>
              <el-button type="danger" size="small" plain @click="handleDel(row.id)"
                >删除</el-button
              >
            </template>
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleView(row.id)"
              v-if="Number(row.checkstatus) == 2"
              >查看</el-button
            >
            <el-button
              type="warning"
              size="small"
              plain
              @click="handleCancel(row.processInstanceId, row.id)"
              v-if="row.checkstatus == 1 && userId == row.chargerCode"
              :loading="cancelLoading && cancelId == row.id"
              >撤销</el-button
            >
          </template>
          <!-- 科研秘书 -->
          <template v-if="verifyRoleType.isKyms()">
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleEdit(row.id)"
              v-if="[-1, 1, 3].includes(Number(row.checkstatus))"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              size="small"
              plain
              @click="handleCheck(row.id, row.processInstanceId)"
              v-if="row.isAuditor"
              >审核</el-button
            >
            <el-button
              type="danger"
              size="small"
              plain
              @click="handleDel(row.id)"
              v-if="[-1, 3].includes(Number(row.checkstatus))"
              >删除</el-button
            >
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleView(row.id)"
              v-if="Number(row.checkstatus) == 2"
              >查看</el-button
            >
          </template>
          <!-- 科研管理员 -->
          <template v-if="verifyRoleType.iskycgly()">
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleEdit(row.id)"
              v-if="[-1, 1, 3].includes(Number(row.checkstatus))"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              size="small"
              plain
              @click="handleCheck(row.id, row.processInstanceId)"
              v-if="row.isAuditor"
              >审核</el-button
            >
            <el-button
              type="danger"
              size="small"
              plain
              @click="handleDel(row.id)"
              v-if="[-1, 3].includes(Number(row.checkstatus))"
              >删除</el-button
            >
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleView(row.id)"
              v-if="[-1, 1, 2, 3].includes(Number(row.checkstatus))"
              >查看</el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-[20px] flex justify-end">
      <el-pagination
        v-bind="pagination"
        @update:current-page="currentChange"
        @update:page-size="sizeChange"
      />
    </div>
  </el-card>
  <EditModal ref="editModalRef" @save-success="handleSearch" />
  <CheckModal ref="checkModalRef" @check-success="handleSearch" />
  <ViewModal ref="viewModalRef" />
  <PersonView ref="personViewModalRef" />
  <exportModal
    v-model="exportVisible"
    :selectList="czhtExportField"
    :title="exportTitle"
    @callBack="handleSelectOk"
  />
</template>

<script setup>
import useTable from "@/hooks/useTable";
import { getList, delRecords, exportRecords, getCount } from "@/api/project/yf/czhtqd";
import { cancelProcess } from "@/api/project/common";
import CheckType from "@/views/project/components/CheckType.vue";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import CommonDateSelect from "@/views/project/components/CommonDateSelect.vue";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import CommonTreeLabel from "@/views/project/components/CommonTreeLabel.vue";
import PersonView from "@/views/project/components/PersonView.vue";
import EditModal from "./components/EditModal.vue";
import CheckModal from "./components/CheckModal.vue";
import ViewModal from "./components/ViewModal.vue";
import exportModal from "@/components/export";
import { ElMessageBox, ElMessage } from "element-plus";
import { czhtExportField } from "@/utils/exportField";
import useCommonFetch from "@/hooks/useCommonFetch";
import useDictFetch from "@/hooks/useDictFetch";
import { verifyRoleType, downloadFile, fomateNumber } from "@/utils/main";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const userId = userStore.userRealId;
const searchFormOpen = ref(false);
const searchFormRef = ref();
const tableRef = ref();
const editModalRef = ref();
const checkModalRef = ref();
const viewModalRef = ref();
const personViewModalRef = ref();
const exportVisible = ref(false);
const exportTitle = "出账合同登记";
const unitList = useCommonFetch("成果归属单位");
const checkStatusList = useDictFetch("bpm_process_instance_status"); //审核状态
const cancelLoading = ref(false);
const cancelId = ref(null);
const countMap = ref({
  total: 0,
  1: 0,
  2: 0,
  3: 0,
});
const searchForm = ref({
  checkStatus: "",
  code: "",
  name: "",
  chargerName: "", //合同负责人
  feeAuthorizeMin: "", //最小合同金额
  feeAuthorizeMax: "", //最大合同金额
  unitId: [], //所属单位
  sourceProjectName: "", //原项目名称
  sourceProjectType: [], //原项目分类
  sourceChargerName: "", //原项目负责人
  chargerTel: "", //负责人电话
  projectStatusId: "", //合同状态
  yfUnitName: "", //供方单位
  yfCode: "", //供方社会信用代码
  yfChargerName: "", //供方联系人名称
  yfTel: "", //供方电话
  checkStatusArr: [], //审核状态
  authorizeDateStart: "", //签订起始日期
  authorizeDateEnd: "", //签订结束日期
});
const { loading, pagination, sizeChange, currentChange, tableData, handleDelete, search } =
  useTable(
    (pagin) =>
      getList({
        pageNum: pagin.pageNum,
        pageSize: pagin.pageSize,
        ...searchForm.value,
      }),
    { getCountStatistics }
  );
getCountStatistics();
//点击新增
const handleAdd = () => {
  editModalRef.value.add();
};
//点击编辑
const handleEdit = (id) => {
  editModalRef.value.edit(id);
};
//点击删除
const handleDel = (id) => {
  handleDelete(delRecords, id);
};
//批量删除
const handleDelSelect = () => {
  //获取当前选中行
  const selectRows = tableRef.value.getSelectionRows();
  if (!selectRows.length) {
    ElMessage({
      message: "请选择要删除的数据！",
      type: "warning",
    });
    return;
  }
  const ids = selectRows.map((item) => item.id);
  handleDelete(delRecords, ids.join(","));
};
//点击审核
const handleCheck = (id, processId) => {
  checkModalRef.value.check(id, processId);
};
//点击撤销
const handleCancel = (processId, cId) => {
  cancelId.value = cId;
  ElMessageBox.confirm("撤销后，该审批流程将自动结束，是否确认取消？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      cancelLoading.value = true;
      const res = await cancelProcess(processId);
      if (res.data) {
        ElMessage({
          message: "操作成功！",
          type: "success",
        });
        handleSearch();
      } else {
        ElMessage({
          message: "操作失败！",
          type: "error",
        });
      }
    } catch (error) {
      console.log(error);
    } finally {
      cancelLoading.value = false;
    }
  });
};
//点击预览详情
const handleView = (id) => {
  viewModalRef.value.view(id);
};
//点击人员姓名
const handleViewPerson = (id) => {
  personViewModalRef.value.view(id);
};
//导出字段选择完毕
const handleSelectOk = async (val) => {
  const cols = val.map((item) => item.prop);
  try {
    const params = {
      ...searchForm.value,
      excelColumn: cols.join(","),
    };
    const res = await exportRecords(params);
    if (res.type != "application/json") {
      downloadFile(res, exportTitle + ".xlsx");
    } else {
      ElMessage({
        message: "导出失败！",
        type: "error",
      });
    }
  } catch (error) {
    console.log(error);
  }
};
//获取检索数量统计
async function getCountStatistics() {
  const params = {
    ...searchForm.value,
    checkStatus: "",
  };
  try {
    const res = await getCount(params);
    countMap.value = {
      total: 0,
      1: 0,
      2: 0,
      3: 0,
    };
    let totalCount = 0;
    res.data.forEach((item) => {
      countMap.value[item.checkstatus] = item.count;
      totalCount += item.count;
    });
    countMap.value.total = totalCount;
  } catch (error) {
    console.log(error);
  }
}
//点击重置
const resetForm = () => {
  searchFormRef.value.resetFields();
  searchForm.value.feeAuthorizeMin = "";
  searchForm.value.feeAuthorizeMax = "";
  searchForm.value.authorizeDateStart = "";
  searchForm.value.authorizeDateEnd = "";
  handleSearch();
};
//执行检索并获取数量统计
const handleSearch = () => {
  search();
  getCountStatistics();
};
</script>

<style scoped lang="scss"></style>
